package com.example.user.player;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Environment;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View.OnClickListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.io.*;
import java.io.File;
import android.media.MediaPlayer;

/**
 * Created by user on 2017/6/19.
 */

public class MusicActivity extends AppCompatActivity{
    private ListView musicListView = null;
    private ImageView imageView = null;
    private ArrayList<Map<String, Object>> listems = null;//需要显示在listview里的信息
    private ArrayList<MusicMedia> musicList = null; //音乐信息列表
    private ImageView btn_play_pause = null;
    public static SeekBar audioSeekBar = null;//定义进度条
    public static TextView textView = null;
    private Intent intent = null;
    private int currentposition = -1;//当前列表那首歌
    private boolean isplay = false;//音乐是否在播放



   // private MediaPlayer mediaPlayer=null;

    private ImageButton button0;
    private  ImageView button1;
    private ImageButton button2;
    private  MusicPlayerService.PlayerBinder mPlayBinder;
    private  ServiceConnection mConnection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
             mPlayBinder=(MusicPlayerService.PlayerBinder)service;

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play);
        Intent serviceintent=new Intent(this,MusicPlayerService.class);
        bindService(serviceintent,mConnection,Context.BIND_AUTO_CREATE);
        init();

    }
    protected void onDestroy() {
        super.onDestroy();
        mPlayBinder.release();

        unbindService(mConnection);

    }

    private void  init(){


        textView  = (TextView)findViewById(R.id.musicinfo);
        button0=(ImageButton)findViewById(R.id.previous);
        button1=(ImageView)findViewById(R.id.play_pause);
        button2=(ImageButton)findViewById(R.id.next);


        button1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if(isplay==true){
                    mPlayBinder.pause();
                    button1.setImageResource(R.drawable.play2);
                    textView.setText(musicList.get(currentposition).getTitle()+" paused ");
                    isplay=false;
                }else{
                if(isplay==false){
                    textView.setText(musicList.get(currentposition).getTitle()+" playing ");
                    mPlayBinder.resume();
                    button1.setImageResource(R.drawable.play);
                    isplay=true;
                }}
            }
        });
        button0.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isplay==true) {

                        if (currentposition > 2) {
                            currentposition = currentposition - 1;
                        }
                        String url = musicList.get(currentposition).getUrl();
                        textView.setText(musicList.get(currentposition).getTitle()+" playing ");
                        mPlayBinder.play(url);

                }
            }
        });
        button2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isplay==true) {
                    if (currentposition < musicList.size()) {
                        currentposition = currentposition + 1;
                    }
                    String url = musicList.get(currentposition).getUrl();
                    textView.setText(musicList.get(currentposition).getTitle()+" playing ");
                    mPlayBinder.play(url);
                }
            }
        });
        musicListView = (ListView)findViewById(R.id.musicLV);

        musicList  = scanAllAudioFiles();
        listems = new ArrayList<Map<String, Object>>();
        for (Iterator iterator = musicList.iterator(); iterator.hasNext();) {
            Map<String, Object> map = new HashMap<String, Object>();
            MusicMedia mp3Info = (MusicMedia) iterator.next();
            map.put("title", mp3Info.getTitle());
            map.put("artist", mp3Info.getArtist());
            map.put("album", mp3Info.getAlbum());
            map.put("duration", mp3Info.getTime());
            map.put("size", mp3Info.getSize());
            map.put("url", mp3Info.getUrl());
            map.put("bitmap", R.drawable.musicfile);
            listems.add(map);
        }
        SimpleAdapter mSimpleAdapter = new SimpleAdapter(
                this,
                listems,
                R.layout.music_item,
                new String[] {"bitmap","title","artist", "size","duration"},
                new int[] {R.id.video_imageView,R.id.video_title,R.id.video_singer,R.id.video_size,R.id.video_duration}
        );
        //listview里加载数据
        musicListView.setAdapter(mSimpleAdapter);
        musicListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                currentposition=position;
                String url=musicList.get(position).getUrl();
                textView.setText(musicList.get(currentposition).getTitle()+" playing ");
                mPlayBinder.play(url);
                isplay=true;
            }
        });
    }
    public ArrayList<MusicMedia> scanAllAudioFiles(){
        //生成动态数组，并且转载数据
        ArrayList<MusicMedia> mylist = new ArrayList<MusicMedia>();

        /*查询媒体数据库
        参数分别为（路径，要查询的列名，条件语句，条件参数，排序）
        视频：MediaStore.Video.Media.EXTERNAL_CONTENT_URI
        图片;MediaStore.Images.Media.EXTERNAL_CONTENT_URI

         */
        Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
        //遍历媒体数据库
        if(null== cursor)
        {
            return null;
        }
        if(cursor.moveToFirst()){
            while (!cursor.isAfterLast()) {
                //歌曲编号
                int id = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
                //歌曲标题
                String tilte = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
                //歌曲的专辑名：MediaStore.Audio.Media.ALBUM
                String album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
                int albumId = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
                //歌曲的歌手名： MediaStore.Audio.Media.ARTIST
                String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
                //歌曲文件的路径 ：MediaStore.Audio.Media.DATA
                String url = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                //歌曲的总播放时长 ：MediaStore.Audio.Media.DURATION
                int duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
                //歌曲文件的大小 ：MediaStore.Audio.Media.SIZE
                Long size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));


                if (size >1024*800){//大于800K
                    MusicMedia musicMedia = new MusicMedia();
                    musicMedia.setId(id);
                    musicMedia.setArtist(artist);
                    musicMedia.setSize(size);
                    musicMedia.setTitle(tilte);
                    musicMedia.setTime(duration);
                    musicMedia.setUrl(url);
                    musicMedia.setAlbum(album);
                    musicMedia.setAlbumId(albumId);
                    Log.e("music disName=", musicMedia.getTitle());//
                    mylist.add(musicMedia);

                }
                cursor.moveToNext();
            }
        }
        cursor.close();
        return mylist;
    }

   /* public  void player(String url){


                 try{     mediaPlayer.reset();
                       mediaPlayer.setDataSource(url);
                       mediaPlayer.setLooping(false);
                        isplay=true;
                        mediaPlayer.prepare();
                        mediaPlayer.start();

                 }catch  (IOException e) {
                      e.printStackTrace();
                 }
    }*/


   /*     protected  void  onStop(){
             super.onStop();
             mediaPlayer.release();
             mediaPlayer=null;
    }*/
}





